﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using mmoss.orm;


public partial class CRMPatientEdit : System.Web.UI.Page
{
    private int CurrentList
    {
        get { return (int)Session["crmListID"]; }
    }
    private User CurrentUser
    {
        get
        {
            return ((User)Session["crmUser"]);
        }
    }
    private CRMListPatient CurrentPatientList
    {
        get
        {
            return dbConn.db.CRMListPatients.Single(p => p.Id == int.Parse(Request.QueryString["listID"].ToString()));
        }
    }
    private Patient CurrentPatient
    {
        get
        {
            if (Request.QueryString["listID"] != null)
            {
                return dbConn.db.CRMListPatients.Single(p => p.Id == int.Parse(Request.QueryString["listID"].ToString())).Patient;
            }
            else
            {
                return new Patient();
            }
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["crmUser"] == null)
        {
            Response.Redirect("login.aspx?msg=user timed out");
        return;
        }

        this.Page.MaintainScrollPositionOnPostBack = true;
        btnSaveInfo.Click += new EventHandler(btnSaveInfo_Click);
        btnSaveStatus.Click += new EventHandler(btnSaveStatus_Click);
        clPrescriptionExpiration.SelectionChanged += new EventHandler(clPrescriptionExpiration_SelectionChanged);
        imgCalendarPrescription.Click += new ImageClickEventHandler(imgCalendarPrescription_Click);
        lnkReturn.Click += new EventHandler(lnkReturn_Click);
        if (!Page.IsPostBack)
        {
            if (CurrentPatient.patientID > 0)
            {
                if (CurrentPatientList.Locked)
                {
                    pnLocked.Visible = true;
                    pnPatientInfo.Visible = false;
                    return;
                }
                loadHistory();
                loadStatuses();
                loadPatientData();
                //lock record
                //CurrentPatientList.Locked = true;
                //dbConn.db.SubmitChanges();
            }
            txtNote.Text = "";
        }
    }

    void lnkReturn_Click(object sender, EventArgs e)
    {
        Response.Redirect("crmList.aspx");
    }

    void clPrescriptionExpiration_SelectionChanged(object sender, EventArgs e)
    {
        //add date to textbox
        txtPrescriptionExpiration.Text = string.Format("{0:MM/dd/yyyy}", clPrescriptionExpiration.SelectedDate);
        clPrescriptionExpiration.Visible = false;
    }

    void imgCalendarPrescription_Click(object sender, ImageClickEventArgs e)
    {
        //laucnh the calendar
        clPrescriptionExpiration.Visible = true;
    }

    void btnSaveStatus_Click(object sender, EventArgs e)
    {
        if (ddlItemOptions.SelectedItem.Value != "")
        {
            //save status
            CRMListPatientHistory l_history = new CRMListPatientHistory();
            l_history.crmListItemID = CurrentList;
            l_history.CRMListPatient = CurrentPatientList;
            l_history.Notes = txtNote.Text;
            l_history.crmListItemID = int.Parse(ddlItemOptions.SelectedItem.Value);
            l_history.User = CurrentUser;
            if (chkCloseCase.Checked)
            {
                CurrentPatientList.Closed = true;
                CurrentPatientList.closedDate = DateTime.Now;
            }
            else
            {
                CurrentPatientList.Closed = false;
            }
            dbConn.db.CRMListPatientHistories.InsertOnSubmit(l_history);
            dbConn.db.SubmitChanges();
            //reload history
            txtNote.Text = "";
            loadHistory();
        }
    }

    void btnSaveInfo_Click(object sender, EventArgs e)
    {
        DateTime? nulldate = null;
        //check flags
        CurrentPatientList.infoUpdated = true;
            CurrentPatientList.redCardDateUpdated = (hidOriginalExpiration.Value != txtPrescriptionExpiration.Text);
        //CurrentPatientList.Locked = false;
        //save info

        CurrentPatient.patientLastName = txtPatientLastName.Text;
        CurrentPatient.patientFirstName = txtPatientFirstName.Text;
        CurrentPatient.patientAddress=txtPatientAddress1.Text;
        CurrentPatient.patientAddress2=txtPatientAddress2.Text;
        CurrentPatient.patientCity=txtPatientCity.Text;
         CurrentPatient.patientZip=txtPatientZip.Text;
        CurrentPatient.patientPhoneHome=txtPatientPhoneHome.Text;
        CurrentPatient.patientPhoneCell=txtPhoneCell.Text;
        CurrentPatient.patientAllowSMS=chkSMS.Checked;
        CurrentPatient.patientEmailList=chkEmail.Checked;

        //load med info
        CurrentPatient.patientDatePrescriptionExpiration = (txtPrescriptionExpiration.Text.Trim() == "" ? nulldate: DateTime.Parse(txtPrescriptionExpiration.Text.Trim()));
        CurrentPatient.patientPrescriptionNumber=txtPrescriptionNumber.Text;
        CurrentPatient.patientDateBirth = (txtDOB.Text.Trim() == "" ? nulldate: DateTime.Parse(txtDOB.Text.Trim()));
        CurrentPatient.patientDriversLicenseNumber = txtDriversLicenseNum.Text;

        //save data
        dbConn.db.SubmitChanges();
        //redirect back to list w/alert
        Response.Write("<script>alert('saved');</script>");
        Response.Redirect("crmlist.aspx");
        
    }
    private void loadHistory()
    {
        gvHistory.DataSource = dbConn.db.CRMListPatientHistories.Where(p => p.CRMListPatient.Patient == CurrentPatient).ToList();
        gvHistory.DataBind();
    }
    private void loadStatuses()
    {
        ddlItemOptions.DataSource = dbConn.db.CRMListItems.Where(p => p.crmListID == int.Parse(Session["crmListID"].ToString())).ToList().OrderBy(p => p.crmListItemOrder);
        ddlItemOptions.DataValueField = "Id";
        ddlItemOptions.DataTextField = "crmListItemDesc";
        ddlItemOptions.DataBind();

        //load states
        ddlPatientState.DataSource = dbConn.db.LookupItems.Where(p => p.lookupTypeID == 1).OrderBy(p => p.lookupOrder).ToList();
        ddlPatientState.DataTextField = "lookupDesc";
        ddlPatientState.DataValueField = "lookupID";
        ddlPatientState.DataBind();
    }
    private void loadPatientData()
    {
        txtPatientLastName.Text = CurrentPatient.patientLastName;
        txtPatientFirstName.Text = CurrentPatient.patientFirstName;
        txtPatientAddress1.Text = CurrentPatient.patientAddress;
        txtPatientAddress2.Text = CurrentPatient.patientAddress2;

        txtPatientCity.Text = CurrentPatient.patientCity;
        txtPatientZip.Text = CurrentPatient.patientZip;
        txtPatientPhoneHome.Text = CurrentPatient.patientPhoneHome;
        txtPhoneCell.Text = CurrentPatient.patientPhoneCell;
        chkSMS.Checked = (CurrentPatient.patientAllowSMS == null || CurrentPatient.patientAllowSMS.Value == false) ? false : true;
        chkEmail.Checked = CurrentPatient.patientEmailList;
        //state
        if (CurrentPatient.patientState != "")
        {
            if (ddlPatientState.Items.FindByText(CurrentPatient.patientState) != null)
            {
                ddlPatientState.Items.FindByText(CurrentPatient.patientState).Selected=true;
            }
        }

        //load med info
        txtPrescriptionExpiration.Text = CurrentPatient.patientDatePrescriptionExpiration.ToString();
        if (CurrentPatient.patientDatePrescriptionExpiration.HasValue)
        {
            hidOriginalExpiration.Value = CurrentPatient.patientDatePrescriptionExpiration.Value.ToString();
        }
        txtPrescriptionNumber.Text = CurrentPatient.patientPrescriptionNumber;
        txtDOB.Text = CurrentPatient.patientDateBirth.ToString();
        txtDriversLicenseNum.Text = CurrentPatient.patientDriversLicenseNumber;
    }
}